package com.speedchina.common.redis.serializer;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author Winter
 * @date 2021年06月09日 10:06
 */
public class StringKeyRedisSerializer implements RedisSerializer<String> {
    private final Charset charset;
    public static final StringKeyRedisSerializer US_ASCII;
    public static final StringKeyRedisSerializer ISO_8859_1;
    public static final StringKeyRedisSerializer UTF_8;
    String prefix = null;

    public StringKeyRedisSerializer() {
        this(StandardCharsets.UTF_8);
    }

    public StringKeyRedisSerializer(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }
    public StringKeyRedisSerializer(String prefix){
        this.prefix = prefix;
        this.charset = StandardCharsets.UTF_8;
    }
    public StringKeyRedisSerializer(String prefix,Charset charset){
        this.prefix = prefix;
        this.charset = charset;
    }

    public String deserialize(@Nullable byte[] bytes) {
        String string = bytes == null ? null : new String(bytes, this.charset);
        return (StringUtils.isEmpty(this.prefix)?string:this.prefix+":"+string);
//        return string;
    }

    public byte[] serialize(@Nullable String string) {
        string = (StringUtils.isEmpty(this.prefix)?"":this.prefix+":")+ string;
        return string == null ? null : string.getBytes(this.charset);
    }

    public Class<?> getTargetType() {
        return String.class;
    }

    static {
        US_ASCII = new StringKeyRedisSerializer(StandardCharsets.US_ASCII);
        ISO_8859_1 = new StringKeyRedisSerializer(StandardCharsets.ISO_8859_1);
        UTF_8 = new StringKeyRedisSerializer(StandardCharsets.UTF_8);
    }
}
